from ctypes.wintypes import tagPOINT
from django.shortcuts import render
# Create your views here.
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.core import serializers
# 认证模块
from django.contrib import auth
# 对应数据库
from django.contrib.auth.models import User
from django.contrib.auth import *
import requests
import json
import numpy as np
import os
import pandas as pd
import re
from OperationTool.Utilities.AutoGetOperator.GetNmaeFunc.getDecisionMethodName import GetDecisionMethodName
from OperationTool.Utilities.AutoGetOperator.GetNmaeFunc.getDistanceName import GetSimilarityName
from OperationTool.Utilities.AutoGetOperator.GetNmaeFunc.getOperatorName import GetOperatorName
from OperationTool.Utilities.AutoGetOperator.GetNmaeFunc.getScoreName import GetScoreName
from OperationTool.Utilities.AutoGetOperator.GetNmaeFunc.getSimilarityName import GetSimilarityName
from OperationTool.main import *
from OperationTool.Utilities.AutoGetOperator.selectPackage import get_func
from OperationTool.Utilities.Plot.SimplePlot import SimpleClass
from OperationTool.Utilities.AutoGetOperator.getOperatorClass import GetOperatorClass
from OperationTool.DataAnalyze.singleOperatorTestFixData import *
from io import BytesIO
import matplotlib
matplotlib.use('Agg')  # 不出现画图的框
import matplotlib.pyplot as plt
import base64


#设置全局变量
g_data = []



# 集结
@require_http_methods(["GET"])
def getMethodName(request):
    response = {}
    # 获得决策方法名称
    decisionMethonClass = GetDecisionMethodName()
    decisionMethon = []
    for i in (decisionMethonClass.getname()):
        decisionMethon.append(i)
    
    #获得距离 (先别用)
    # DistanceNameClass = GetSimilarityName()
    # Distance = []
    # for i in (DistanceNameClass.getname()):
    #     Distance.append(i)

    #获取算子名称
    OperatorNameClass = GetOperatorName()
    operatorName =[]
    for i in (OperatorNameClass.getname()):
        operatorName.append(i)
        
    #获取得分函数名称
    scoreNameClass = GetScoreName()
    scoreName =[]
    for i in (scoreNameClass.getname()):
        scoreName.append(i)

    #获取得分函数名称(先别用)
    # SimilarityNameClass=GetSimilarityName()
    # similarityName = []
    # for i in (SimilarityNameClass.getname()):
    #     similarityName.append(i)
    try:
        #返回需要的数据
        response['scoreName'] = scoreName
        response['operatorName'] = operatorName
        response['decisionMethon'] = decisionMethon
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)
    

@require_http_methods(["GET"])
def singleAggregate(request):
    response = {}
    try:
        body = json.loads(request.GET.get('body'))
        response['body'] = body
        QMin = body['QMin']
        QMax = body['QMax']
        # 判断缺少输入数据
        if g_data == []:
            response['msg'] = '导入数据为空'
            response['error_num'] = 1
            return JsonResponse(response)
        if QMin == "" or QMax == "":
            response['msg'] = 'Q值范围数据不合法'
            response['error_num'] = 1
            return JsonResponse(response)

        QMin = int(float(QMin))
        QMax = int(float(QMax))
        #调用算子集结
        matrix=[]
        score = []
        for i in range(QMin,QMax):
            ex = Polymerization(q=i,decision_group=g_data)
            matrix.append(ex.getMatrix())
            score.append(ex.getResult())
        # # 展示简单二维图将map2D设置为True，其他展示的图设置为False，example中只展示图，不保存任何数据
        operator=SingleOperatorTestFixData(map2D=True,
        mapRadar=True, mapDeviation=False,imgShow=True, imgSaving=False)
        operator.set_dataGroup(g_data)
        operator.q_analyze(2, 10)
        img2D = "data:image/png;base64,"+operator.getImg2D()
        imgRadar = "data:image/png;base64,"+operator.getImgRadar()
        # print("img:")
        # print(img2D)
        # print(imgRadar)
        # ims = operator.q_analyze(2, 10)
        #imd =   "data:image/png;base64,"+ ims
        #print(imd)
        #需要返回的数据
        response['aggregationMatrix'] = str(matrix)
        response['finalScore'] = score
        response['img2D'] = img2D
        response['imgRadar'] = imgRadar
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)
@require_http_methods(["GET"])
def multipleAggregate(request):
    response = {}
    try:
        body = json.loads(request.GET.get('body'))
        response['body'] = body
        QMin = body['QMin']
        QMax = body['QMax']
        # 判断缺少输入数据
        if g_data == []:
            response['msg'] = '导入数据为空'
            response['error_num'] = 1
            return JsonResponse(response)
        if QMin == "" or QMax == "":
            response['msg'] = 'Q值范围数据不合法'
            response['error_num'] = 1
            return JsonResponse(response)

        QMin = int(float(QMin))
        QMax = int(float(QMax))
        #调用算子集结
        matrix=[]
        score = []
        for i in range(QMin,QMax):
            ex = Polymerization(q=i,decision_group=g_data)
            matrix.append(ex.getMatrix())
            score.append(ex.getResult())
        # # 展示简单二维图将map2D设置为True，其他展示的图设置为False，example中只展示图，不保存任何数据
        # operator=SingleOperatorTestFixData(map2D=True,
        # mapRadar=False, mapDeviation=False,imgShow=True, imgSaving=False)
        # operator.set_dataGroup(g_data)
        # ims = operator.q_analyze(2, 10)
        # imd = "data:image/png;base64," + ims
        #print(imd)
        #需要返回的数据
        response['aggregationMatrix'] = str(matrix)
        response['finalScore'] = score
        # response['img'] = imd
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)
@require_http_methods(["GET"])
def directAggregate(request):
    response = {}
    try:
        body = json.loads(request.GET.get('body'))
        response['body'] = body
        QMin = body['QMin']
        QMax = body['QMax']
        # 判断缺少输入数据
        if g_data == []:
            response['msg'] = '导入数据为空'
            response['error_num'] = 1
            return JsonResponse(response)
        if QMin == "" or QMax == "":
            response['msg'] = 'Q值范围数据不合法'
            response['error_num'] = 1
            return JsonResponse(response)

        QMin = int(float(QMin))
        QMax = int(float(QMax))
        #调用算子集结
        matrix=[]
        score = []
        for i in range(QMin,QMax):
            ex = Polymerization(q=i,decision_group=g_data)
            matrix.append(ex.getMatrix())
            score.append(ex.getResult())
        # # 展示简单二维图将map2D设置为True，其他展示的图设置为False，example中只展示图，不保存任何数据
        # operator=SingleOperatorTestFixData(map2D=True,
        # mapRadar=False, mapDeviation=False,imgShow=True, imgSaving=False)
        # operator.set_dataGroup(g_data)
        # ims = operator.q_analyze(2, 10)
        # imd = "data:image/png;base64," + ims
        #print(imd)
        #需要返回的数据
        response['aggregationMatrix'] = str(matrix)
        response['finalScore'] = score
        # response['img'] = imd
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)

# 上传excel
@require_http_methods(["POST"])
def excel(request):
    response = {}
    received_file = request.FILES.get('excel')
    # print(received_file)
    filename = os.path.join('media', received_file.name)
    saveFile(received_file,filename)
    userName = received_file.name
    df_dict = pd.read_excel(filename, sheet_name=None)
    matrixSize = len(df_dict.keys())#获取矩阵个数+
    for key in df_dict.keys():
        tmp1 =[]
        df = pd.read_excel(filename, sheet_name=key)
        arr=np.array(df)
        for i in range(0,len(arr)):
            tmp2 = []
            for j in range(1,len(arr[0])):
                strdata = re.findall("\d+\.?\d*", arr[i][j])
                for i in range(len(strdata)):  # 列表元素转化为int格式
                    strdata[i] = float(strdata[i])
                floatData = ([strdata[0],strdata[1]],[strdata[2],strdata[3]])
                tmp2.append(floatData)
            tmp1.append(tmp2)
        g_data.append(tmp1)
    #print(g_data)
    try:
        #需要返回的数据
        response['excelName'] = received_file.name
        response['msg'] = 'success'
        response['error_num'] = 0
    except  Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
    return JsonResponse(response)

# 保存上传的文件
def saveFile(received_file, filename):    
    with open(filename, 'wb')as f:
        f.write(received_file.read())
    # ff = open(filename,'wb')
    # for chunk in received_file.chunks():
    #     ff.write(chunk)
    # ff.close()
# 读取上传的文件内容，并返回
def readFile(filename):
    with open(filename,'r')as f:
        content = f.read()
    return JsonResponse(content)


